// 使用组件
layui.use(['layer', 'table', 'laydate'], function(){
  var layer = layui.layer;
  var table = layui.table;
  var laydate = layui.laydate;

  //加载数据
  table.render({
      elem: '#logList'
      , url: 'log/list/' //数据接口
      , headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
      , page: {
          layout: ['count', 'prev', 'page', 'next', 'skip']
          , prev: '上一页'
          , next: '下一页'
          , limit: 10
      }
      , request: {
          pageName: 'pageNum' //页码的参数名称，默认：page
          , limitName: 'pageSize' //每页数据量的参数名，默认：limit
      }
      , parseData: function (res) { //res 即为原始返回的数据
          return {
              "code": res.code, //解析接口状态
              "msg": res.msg, //解析提示文本
              "count": res.data.total,
              "data": res.data.list, //解析数据列表
          };
      }
      , done: function (res, curr, count) {
          // 解决无数据table样式错乱
          if(count == 0){
              $("th[data-key='1-0-3']").css("border-right", "0");
          }
      }
      , cols: [[ //表头
          {field: 'createTime', width: 170, title: '时间'}
          , {field: 'ip', width: 140, title: '来源'}
          , {title: '日志信息', templet: function (d){
            return escape(d.content).substring(0, 100);
          }}
          , {title: '操作', width: 100, toolbar: '#operates', fixed: 'right'}
      ]]
  });

  laydate.render({
      elem: '#time' //指定元素
      ,type: 'datetime'
      ,trigger: 'click'
      ,range: ',' //开启日期范围，默认使用“-”分割
    });

  $("#search").click(function(){
      var ip = $("#ip").val();
      var content = $("#content").val();
      var time = $("#time").val();
      table.reload('logList', {page: {curr: 1}, where: {"content":content, "ip":ip, "time":time}});
  });

  initSearch("#content");

  table.on('tool(logList)', function (obj) {
    var data = obj.data;
    var layEvent = obj.event;
    if (layEvent === 'view') { //详情
      var width = (windowWidth > 800? 800 : windowWidth) + 'px';
      parent.layer.open({
          area: width,
          type: 1,
          title: '日志详情',
          content: '<pre>' + escape(data.content) + '</pre>'
      });
    }
  });

  $("#clean").click(function(){
    layer.confirm('确认清空日志吗?', function(index) {
        $.ajax({
            type: "POST",
            url: "log/clean",
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if (result.code == 0) {
                    layer.msg('操作成功', {icon: 6});
                    table.reload('logList');
                }else{
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        layer.close(index);
    });
  });
});
